package com.nami.ucenter.application.login;

import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import com.nami.ucenter.domain.model.UserModel;
import com.nami.ucenter.domain.port.repository.UserRepository;
import com.nami.ucenter.facade.login.UserLoginFacade;
import com.nami.ucenter.facade.login.request.query.UserLoginQry;
import com.nami.ucenter.facade.login.response.UserLogin;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.system.api.model.LoginUser;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@AllArgsConstructor
public class UserLoginFacadeImpl implements UserLoginFacade {

    private final UserRepository userRepository;

    @Override
    public UserLogin execute(UserLoginQry request) {
        UserModel exist = userRepository.getUserByMobile(request.getMobile());
        if (exist == null) {
            throw new ServiceException("用户不存在！");
        }
        UserLogin login = new UserLogin();
        login.setUserId(exist.getUserId());

//        StpUtil.login(exist.getUserId());
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(Long.valueOf(exist.getUserId()));
        loginUser.setClientKey("fdsdfdf2323hfdgk5645");
        loginUser.setDeviceType("ios");
        loginUser.setUserType(UserType.APP_USER.getUserType());
        SaLoginModel model = new SaLoginModel();
        model.setDevice("pc");
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期


        model.setExtra(LoginHelper.TENANT_KEY, exist.getAppKey());
        model.setExtra(LoginHelper.USER_KEY, exist.getUserId());
        model.setExtra(LoginHelper.CLIENT_KEY, "fdsdfdf2323hfdgk5645");
        // 生成token
        LoginHelper.login(loginUser, model);

        String tokenValue = StpUtil.getTokenValue();
        // 调用注册中心，获取服务列表，
        login.setGateUrl("ws://localhost:30000/ws");
        login.setToken(tokenValue);
        return null;
    }

}
